package com.tanxi521.commandmanager.Listener;

import lombok.extern.slf4j.Slf4j;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;

import java.util.ArrayList;
import java.util.List;

public class CraftTableListener implements Listener {

    public static final List<String> table = new ArrayList<>();
    public static final List<String> allowBlock = new ArrayList<>();
    public static final String FORBIDDEN_BLOCK = "§c§l工作台附近禁止除圆石|草方块|泥土|玻璃|石砖|橡木木板之外的方块";

    static {
        table.add("EXTENDEDCRAFTING_TABLE_BASIC");
        table.add("EXTENDEDCRAFTING_TABLE_ADVANCED");
        table.add("EXTENDEDCRAFTING_TABLE_ELITE");
        table.add("EXTENDEDCRAFTING_TABLE_ULTIMATE");

        allowBlock.add("COBBLESTONE");
        allowBlock.add("GRASS");
        allowBlock.add("DIRT");
        allowBlock.add("GLASS");
        allowBlock.add("WOOD");
        allowBlock.add("AIR");
        allowBlock.add("SMOOTH_BRICK");
    }

    @EventHandler
    public void onFlowerPlace(BlockPlaceEvent event) {

    }

    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event) {
        Player player = event.getPlayer();
        Block placedBlock = event.getBlockPlaced();
        String type = String.valueOf(placedBlock.getType());
        // 获取传入的范围参数（这里简化为范围为一格）
        int range = 1;

        // 检查是否放置的是被禁止的方块类型
        if (table.contains(type)) {
            // 检查周围方块，如果有被禁止的方块类型，阻止放置
            for (int dx = -range; dx <= range; dx++) {
                for (int dy = -range; dy <= range; dy++) {
                    for (int dz = -range; dz <= range; dz++) {
                        Block nearbyBlock = placedBlock.getRelative(dx, dy, dz);
                        String nearbyMaterial = String.valueOf(nearbyBlock.getType());
                        if ((!allowBlock.contains(nearbyMaterial)) && (!table.contains(nearbyMaterial))) {
                            event.setCancelled(true);
                            player.sendMessage(FORBIDDEN_BLOCK);
                            return;
                        }
                    }
                }
            }
        } else {
            for (int dx = -range; dx <= range; dx++) {
                for (int dy = -range; dy <= range; dy++) {
                    for (int dz = -range; dz <= range; dz++) {
                        Block nearbyBlock = placedBlock.getRelative(dx, dy, dz);
                        String nearbyMaterial = String.valueOf(nearbyBlock.getType());
                        if (table.contains(nearbyMaterial)) {
                            event.setCancelled(true);
                            player.sendMessage(FORBIDDEN_BLOCK);
                            return;
                        }
                    }
                }
            }
        }
    }

}
